package site.beanyon.now.service;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import site.beanyon.now.mapper.UserMapper;
import site.beanyon.now.model.dto.UserDTO;
import site.beanyon.now.model.po.UserPO;
import site.beanyon.now.util.PasswordUtils;
import site.beanyon.now.util.StringUtils;

import java.util.List;

/**
 * 用户服务类
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    /**
     * 获取当前用户对象
     *
     * @return 用户对象
     */
    public UserDTO getCurrentUser() {
        return ((UserDTO) SecurityUtils.getSubject().getPrincipal());
    }

    /**
     * 添加用户
     *
     * @param tel      登录账号
     * @param password 登录密码
     * @param salt     密码盐
     * @return 是否添加成功
     */
    @Override
    public boolean insertUser(String tel, String password, String salt) {
        String newPassword = PasswordUtils.addSaltToPassword(password, salt);
        return this.userMapper.insertUser(tel, newPassword, salt).equals(1);
    }

    /**
     * 根据登录账号获取用户对象
     *
     * @param tel 用户登录账号/手机号码
     * @return UserPO对象
     */
    @Override
    public UserPO getUser(String tel) {
        return this.userMapper.queryUserByTel(tel);
    }

    /**
     * 获取用户有登录行为的天数
     *
     * @return 用户有登录行为的天数
     */
    @Override
    public Integer getLoginDayCount() {
        Integer dayCount = this.userMapper.queryUserLoginDayCount(this.getCurrentUser().getId());
        if (dayCount == null) {
            dayCount = 0;
        }

        return dayCount + 1;
    }

    /**
     * 更新用户信息
     *
     * @param name     用户名
     * @param birthday 用户生日
     * @param gender   用户性别
     */
    @Override
    public void updateUserInfo(String name, String birthday, String gender) {
        Integer userId = this.getCurrentUser().getId();

        // 更新用户性别
        if (!StringUtils.isEmpty(gender)) {
            this.userMapper.updateUserGender(userId, gender);
        }

        // 更新用户名
        if (!StringUtils.isEmpty(name.trim().replace(" ", ""))) {
            this.userMapper.updateUserName(userId, name);
        }

        // 更新用户生日
        if (!StringUtils.isEmpty(birthday)) {
            this.userMapper.updateUserBirthday(userId, birthday);
        }
    }

    /**
     * 获取全部用户
     *
     * @return 用户列表
     */
    @Override
    public List<UserPO> getAllUsers() {
        return this.userMapper.listUser();
    }
}
